package com.h3c.ptability.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.h3c.ptability.bo.ElectronicSignBO;
import com.h3c.ptability.bo.ElectronicSignPreviewBO;
import com.h3c.ptability.dto.electronicSign.DocTemplateAndFeatureDTO;
import com.h3c.ptability.dto.electronicSign.PtEsignDocTemplateDTO;
import com.h3c.ptability.entity.PtEsignDocFeature;
import com.h3c.ptability.entity.PtEsignDocTemplate;
import com.h3c.ptability.mapstruct.PtEsignDocFeatureMapstruct;
import com.h3c.ptability.mapstruct.PtEsignDocTemplateMapstruct;
import com.h3c.ptability.service.IPtEsignDocFeatureService;
import com.h3c.ptability.service.IPtEsignDocTemplateService;
import com.h3c.ptability.support.ResultData;
import com.h3c.ptability.utils.PageUtils;
import com.h3c.ptability.vo.NameAndIdVO;
import com.h3c.ptability.vo.PtEsignDocTemplateVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.List;


/**
 * 电子签doc文件模板控制层
 *
 * @author chenyifan
 * @since 2022-05-19 10:46:24
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/ptEsignDocTemplate")
public class PtEsignDocTemplateController {
    /**
     * 服务对象
     */
    private final IPtEsignDocTemplateService ptEsignDocTemplateService;

    private final IPtEsignDocFeatureService docFeatureService;

    /**
     * 保存模板
     *
     * @return
     */
    @PostMapping("/saveTemplateFile")
    public ResultData<String> saveTemplate(@RequestBody DocTemplateAndFeatureDTO templateAndFeatureDTO) {
        try {
            ptEsignDocTemplateService.saveTemplate(templateAndFeatureDTO);
            return ResultData.success("保存模板成功");
        } catch (Exception e) {
            log.error("保存模板文件失败", e);
            return ResultData.fail("保存模板文件失败");
        }

    }

    /**
     * 编辑模板
     *
     * @return
     */
    @PostMapping("/updateTemplateFile")
    public ResultData<String> updateTemplate(@RequestBody DocTemplateAndFeatureDTO templateAndFeatureDTO) {
        try {
            if (!StringUtils.hasText(templateAndFeatureDTO.getDocTemplateDTO().getTemplateId())) {
                return ResultData.fail("请选中要编辑的模板");
            }
            ptEsignDocTemplateService.updateTemplate(templateAndFeatureDTO);
            return ResultData.success("更新模板成功");
        } catch (Exception e) {
            log.error("保存模板文件失败", e);
            return ResultData.fail("更新模板文件失败");
        }

    }

    /**
     * 条件分页查询模板
     *
     * @param docTemplateDTO
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/pageTemplate")
    public ResultData<IPage<PtEsignDocTemplateVO>> getTemplatePage(PtEsignDocTemplateDTO docTemplateDTO,
                                                                   @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                                   @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<PtEsignDocTemplate> queryWrapper = new QueryWrapper<PtEsignDocTemplate>().lambda();
        if (StringUtils.hasText(docTemplateDTO.getDocType())) {
            queryWrapper.eq(PtEsignDocTemplate::getDocType, docTemplateDTO.getDocType());
        }
        if (StringUtils.hasText(docTemplateDTO.getAppId())) {
            queryWrapper.eq(PtEsignDocTemplate::getAppId, docTemplateDTO.getAppId());
        }
        if (StringUtils.hasText(docTemplateDTO.getDocName())) {
            queryWrapper.like(PtEsignDocTemplate::getDocName, docTemplateDTO.getDocName());
        }
        Page<PtEsignDocTemplate> templatePage = ptEsignDocTemplateService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<PtEsignDocTemplateVO> voList = PtEsignDocTemplateMapstruct.INSTANCE.entityList2VoList(templatePage.getRecords());
        for (PtEsignDocTemplateVO record : voList) {
            List<PtEsignDocFeature> docFeatures = docFeatureService.list(new QueryWrapper<PtEsignDocFeature>().lambda()
                    .eq(PtEsignDocFeature::getTemplateId, record.getTemplateId())
            );
            record.setFeatureVOS(PtEsignDocFeatureMapstruct.INSTANCE.EntityList2VOList(docFeatures));
        }
        return ResultData.data(PageUtils.toPage(templatePage, voList));
    }

    /**
     * 删除文件模板接口
     *
     * @param templateId
     * @return
     */
    @GetMapping("/deleteTemplate")
    public ResultData<String> deleteTemplate(String templateId) {
        try {
            ptEsignDocTemplateService.deleteTemplate(templateId);
            return ResultData.success("删除成功");
        } catch (Exception e) {
            log.error("删除模板失败:{}", e.getMessage());
            return ResultData.success("删除成功");
        }
    }

    @GetMapping("/getDocNameList")
    public ResultData<List<NameAndIdVO>> getDocNameList(@RequestParam(required = false) String appId) {
        try {
            return ResultData.data(ptEsignDocTemplateService.getDocNameList(appId), "获取成功");
        } catch (Exception e) {
            log.error("获取失败:{}", e.getMessage());
            return ResultData.fail("获取失败");
        }
    }

    /**
     * 预览签署文件
     *
     * @param signPreviewBO 预览bo
     * @return
     */
    @PostMapping("/getDocNameList")
    public ResultData<String> previewPdfTemplate(@RequestBody ElectronicSignPreviewBO signPreviewBO) {
        try {
            File pdfTemplate = ptEsignDocTemplateService.getPdfTemplate(ptEsignDocTemplateService.getById(signPreviewBO.getTemplateId()),
                    signPreviewBO.getUserData());
            byte[] bytes = FileUtil.readBytes(pdfTemplate);
            return ResultData.data(Base64Utils.encodeToString(bytes));
        } catch (Exception e) {
            log.error("预览失败", e);
            return ResultData.fail("预览失败", e.getMessage());
        }
    }
}

